package org.walklink.common.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * 对象和字节数组相互转换
 *
 * @author lidishan
 */
public class ObjectAndByteUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(ObjectAndByteUtil.class);

    /**
     * 对象转数组
     *
     * @param obj 对象
     */
    public static byte[] toByteArray(Object obj) {
        try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
             ObjectOutputStream oos = new ObjectOutputStream(bos)) {
            oos.writeObject(obj);
            oos.flush();
            return bos.toByteArray();
        } catch (IOException ex) {
            LOGGER.error("[ERROR_toByteArray] obj={}", obj, ex);
            return null;
        }
    }

    /**
     * 数组转对象
     *
     * @param bytes 字节数组
     */
    public static Object toObject(byte[] bytes) {
        try (ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
             ObjectInputStream ois = new ObjectInputStream(bis)) {
            return ois.readObject();
        } catch (IOException | ClassNotFoundException ex) {
            LOGGER.error("[ERROR_toObject] error", ex);
            return null;
        }
    }

}